package cn.stylefeng.guns.modular.rest.hxStorageStock.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicGoods;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsService;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageOffShelf;
import cn.stylefeng.guns.modular.hx.storage.enums.CommonVariables;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageOffShelfParam;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStorageOffShelfResult;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageOffShelfService;
import cn.stylefeng.guns.modular.rest.aop.UserAop;
import cn.stylefeng.guns.sys.modular.system.entity.Menu;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.EmptyStackException;
import java.util.List;

/**
 * 下架任务表控制器
 *
 * @author 
 * @Date 2023-09-13 17:26:11
 */
@Controller
@RequestMapping("/rest/hxStorageOffShelf")
public class HxAppStorageOffShelfController extends BaseController {

    @Autowired
    private HxStorageOffShelfService hxStorageOffShelfService;

    @Autowired
    private UserAop userAop;

    @Autowired
    private HxBasicGoodsService hxBasicGoodsService;

    /**
     * 新增接口
     *
     * @author 
     * @Date 2023-09-13
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(HxStorageOffShelfParam hxStorageOffShelfParam, Long id) {
        //增加下架任务权限校验
        User user = userAop.getUser();
        List<Long> roleList = new ArrayList<Long>();
        String[] split = user.getRoleId().split(",");//以逗号分割
        for (String string2 : split) {
            roleList.add(Long.parseLong(string2));
        }
        List<Menu> mlist = userService.getAppletsPermissionlist(roleList,"/rest/hxStorageOffShelf/addItem");
        if(mlist.size() == 0) {
            return ResponseData.error("权限异常");
        }
        if (ToolUtil.isEmpty(hxStorageOffShelfParam)||ToolUtil.isEmpty(id))
            throw new EmptyStackException();
        hxStorageOffShelfParam.setDeptId(user.getDeptId());
        hxStorageOffShelfParam.setCreateUserName(user.getName());
        hxStorageOffShelfParam.setCreateTime(new Date());
        hxStorageOffShelfParam.setOperateId(user.getOperateId());
        String s = this.hxStorageOffShelfService.addItem(hxStorageOffShelfParam, id);
        switch (s) {
            case "error1":
                return ResponseData.error("查无库存");
            case "error2":
                return ResponseData.error("目的库位不符");
            case "error3":
                return ResponseData.error("请选择合适库位");
            case "error4":
                return ResponseData.error("不可以跨仓");
            case "error5":
                return ResponseData.error("不可重复添加下架任务");
            case "error6":
                return ResponseData.error("与目标库位绑定商品不一致");
            default:
                return ResponseData.success(s);
        }
    }

    /**
     * 领取接口
     *
     * @author 
     * @Date 2023-09-13
     */
    @RequestMapping("/receive")
    @ResponseBody
    public ResponseData receive(HxStorageOffShelfParam hxStorageOffShelfParam) {
        User user = userAop.getUser();
        List<Long> roleList = new ArrayList<Long>();
		String[] split = user.getRoleId().split(",");//以逗号分割
        for (String string2 : split) {
        	roleList.add(Long.parseLong(string2));
        }
        List<Menu> mlist = userService.getAppletsPermissionlist(roleList,"/rest/hxStorageOffShelf/receive");
        if(mlist.size() == 0) {
            return ResponseData.error("权限异常");
        }
        hxStorageOffShelfParam.setStatus(CommonVariables.RECEIVED.getDesc());
        hxStorageOffShelfParam.setReceiveTime(new Date());
        hxStorageOffShelfParam.setOffUserName(user.getName());
        hxStorageOffShelfParam.setOffUserId(user.getUserId());
        HxStorageOffShelf hxStorageOffShelf = new HxStorageOffShelf();
        BeanUtils.copyProperties(hxStorageOffShelfParam,hxStorageOffShelf);
        if(user.getOperateId() != null) {
        	synchronized(user.getOperateId()) {
                HxStorageOffShelf offShelf = hxStorageOffShelfService.getById(hxStorageOffShelf.getId());
                if (offShelf.getStatus().equals(CommonVariables.UNCLAIMED.getDesc())){
                	Integer count = hxStorageOffShelfService.lambdaQuery()
                	.eq(HxStorageOffShelf::getStockId, offShelf.getStockId())
                	.ne(HxStorageOffShelf::getStatus, "作废")
                	.ne(HxStorageOffShelf::getStatus, "已完成")
                	.count();
                	if(count > 1) {
                        return ResponseData.error("系统检测到有重复下架任务，请作废1条");
                	}
                    this.hxStorageOffShelfService.updateById(hxStorageOffShelf);
                } else {
                    return ResponseData.error("已被领取");
                }
        	}
        } else {
            return ResponseData.error("账号不支持下架");
        }
        return ResponseData.success();
    }

    /**
     * 确认用户接口
     *
     * @author
     * @Date 2023-09-13
     */
    @RequestMapping("/findUser")
    @ResponseBody
    public ResponseData findUser(Long offUserId) {
        if (ToolUtil.isEmpty(offUserId))
            throw new EmptyStackException();
        User user = userAop.getUser();
        if (user.getUserId().equals(offUserId)){
            return ResponseData.success();
        }else {
            return ResponseData.error("不可查看别人的任务");
        }
    }

    /**
     * 确认用户接口
     *
     * @author
     * @Date 2023-09-13
     */
    @RequestMapping("/findUser2")
    @ResponseBody
    public ResponseData findUser2(String account) {
        if (ToolUtil.isEmpty(account))
            throw new EmptyStackException();
        User user = userAop.getUser();
        if (user.getAccount().equals(account)){
            return ResponseData.success();
        }else {
            return ResponseData.error("不可查看别人的任务！！！");
        }
    }
    
    @Autowired
    private UserService userService;

    /**
     * 撤销接口
     * @author
     * @Date 2023-09-13
     */
    @RequestMapping("/revokeReceive")
    @ResponseBody
    public ResponseData revokeReceive(Long id) {
		User user = userAop.getUser();
        if(user.getOperateId() != null) {
        	synchronized(user.getOperateId()) {
        		HxStorageOffShelf hxStorageOffShelf = hxStorageOffShelfService.getById(id);
        		if(!hxStorageOffShelf.getStatus().equals("已领取")) {
                    return ResponseData.error("任务不存在或已完成");
        		}
                List<Long> roleList = new ArrayList<Long>();
        		String[] split = user.getRoleId().split(",");//以逗号分割
                for (String string2 : split) {
                	roleList.add(Long.parseLong(string2));
                }
                List<Menu> mlist = userService.getAppletsPermissionlist(roleList,"/rest/hxStorageOffShelf/revokeReceive");
                if(mlist.size() == 0) {
                    List<Menu> mlist2 = userService.getAppletsPermissionlist(roleList,"/rest/hxStorageOffShelf/revokeReceiveMe");
                    if(mlist2.size() == 0) {
                    	return ResponseData.error("权限异常");
                    } else {
                    	if(!user.getUserId().equals(hxStorageOffShelf.getOffUserId())) {
                        	return ResponseData.error("权限异常");
                    	}
                    }
                }
                HxStorageOffShelf hxStorageOffShelf2 = new HxStorageOffShelf();
                hxStorageOffShelf2.setStatus(CommonVariables.UNCLAIMED.getDesc());
                hxStorageOffShelf2.setId(id);
                this.hxStorageOffShelfService.updateById(hxStorageOffShelf2);
        	}
        } else {
            return ResponseData.error("账号不支持下架");
        }
        return ResponseData.success();
    }
    
    /**
     * 编辑接口
     *
     * @author
     * @Date 2023-09-13
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(HxStorageOffShelfParam hxStorageOffShelfParam) {
        this.hxStorageOffShelfService.update(hxStorageOffShelfParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author 
     * @Date 2023-09-13
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(HxStorageOffShelfParam hxStorageOffShelfParam) {
        this.hxStorageOffShelfService.delete(hxStorageOffShelfParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author 
     * @Date 2023-09-13
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(Long id) {
        if (ToolUtil.isEmpty(id))
            throw new EmptyStackException();
        HxStorageOffShelf detail = this.hxStorageOffShelfService.getById(id);

        // 商品箱规以及折箱计算
        detail.setBoxNumStr("-");
        StringBuffer boxNumStr = new StringBuffer();
        if(ToolUtil.isNotEmpty(detail.getGoodsId())){
            HxBasicGoods hxBasicGoods = this.hxBasicGoodsService.getById(detail.getGoodsId());
            if(ToolUtil.isNotEmpty(hxBasicGoods) && ToolUtil.isNotEmpty(hxBasicGoods.getBoxSpecs())){
                try {
                    detail.setBoxSpecs(hxBasicGoods.getBoxSpecs());
                    BigDecimal boxSpecs = new BigDecimal(hxBasicGoods.getBoxSpecs());
                    if(ToolUtil.isNotEmpty(detail.getKcNum())){
                        BigDecimal zs = new BigDecimal(detail.getKcNum()).divide(boxSpecs, 0, RoundingMode.DOWN);
                        if(zs.compareTo(BigDecimal.ZERO) > 0){
                            boxNumStr.append(zs).append("箱");
                        }
                        BigDecimal ys = new BigDecimal(detail.getKcNum()).remainder(boxSpecs);
                        if(ys.compareTo(BigDecimal.ZERO) > 0){
                            boxNumStr.append(ys.setScale(0,BigDecimal.ROUND_UP)).append(hxBasicGoods.getJibenUnit());
                        }
                    }
                    if(boxNumStr.length() > 0){
                        detail.setBoxNumStr(boxNumStr.toString());
                    }
                }catch (Exception e){
                }
            }
        }


        return ResponseData.success(detail);
    }
    
    /**
     * 确认完成下架任务接口
     *
     * @author
     * @Date 2023-09-13
     */
    @RequestMapping("/offShelf")
    @ResponseBody
    public ResponseData offShelf(Long id, BigDecimal xjNum) {

        if (ToolUtil.isEmpty(id))
            throw new EmptyStackException();

        if (xjNum.compareTo(BigDecimal.ZERO) < 0){
            return ResponseData.error("下架数量必须大于0！");
        }
        User user = userAop.getUser();
        String s = "";
        synchronized (user.getUserId()){
            s = this.hxStorageOffShelfService.offShelf(id,user,xjNum);
        }
        if (s.equals("success")){
            return ResponseData.success();
        }else{
            return ResponseData.error(s);
        }
    }





    /**
     * 查询列表
     *
     * @author 
     * @Date 2023-09-13
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(HxStorageOffShelfParam hxStorageOffShelfParam,String condition ) {
        return this.hxStorageOffShelfService.findPageBySpec(hxStorageOffShelfParam,condition);
    }
    /**
     * 查询列表
     *
     * @author
     * @Date 2023-09-13
     */
    @ResponseBody
    @RequestMapping("/findOffShelfListPage")
    public LayuiPageInfo findOffShelfListPage(String condition, Integer current) {
        if (ToolUtil.isEmpty(current))
            return null;
        User user = userAop.getUser();
        HxStorageOffShelf hxStorageOffShelf = new HxStorageOffShelf();
        hxStorageOffShelf.setStatus(CommonVariables.desc(current));
        hxStorageOffShelf.setDeptId(user.getDeptId());
        hxStorageOffShelf.setOperateId(user.getOperateId());
        LayuiPageInfo offShelfList = hxStorageOffShelfService.findOffShelfListPage(hxStorageOffShelf, condition);
        return offShelfList;
    }
    /**
     * 查询列表
     *
     * @author
     * @Date 2023-09-13
     */
    @ResponseBody
    @RequestMapping("/findOffShelfList")
    public ResponseData findOffShelfList(String condition, Integer current) {
        if (ToolUtil.isEmpty(current))
            return null;
        User user = userAop.getUser();
        HxStorageOffShelf hxStorageOffShelf = new HxStorageOffShelf();
        hxStorageOffShelf.setStatus(CommonVariables.desc(current));
        hxStorageOffShelf.setDeptId(user.getDeptId());
        hxStorageOffShelf.setOperateId(user.getOperateId());
        List<HxStorageOffShelfResult> offShelfList = hxStorageOffShelfService.findOffShelfList(hxStorageOffShelf, condition);
        return ResponseData.success(offShelfList);
    }
    
    /**
     * 待领取加急置顶接口
     */
    @RequestMapping("/top")
    @ResponseBody
    public ResponseData top(HxStorageOffShelfParam hxStorageOffShelfParam){
        //校验是否有加急置顶权限
        User user = userAop.getUser();
        List<Long> roleList = new ArrayList<Long>();
        String[] split = user.getRoleId().split(",");//以逗号分割
        for (String string2 : split) {
            roleList.add(Long.parseLong(string2));
        }
        List<Menu> mlist = userService.getAppletsPermissionlist(roleList,"/rest/hxStorageOffShelf/top");
        if(mlist.size() == 0) {
            return ResponseData.error("权限异常");
        }

        //校验id是否为空
        if (ToolUtil.isEmpty(hxStorageOffShelfParam.getId())){
            return ResponseData.error("id不能为空");
        }
        //将task_flag 设置为急置顶
        hxStorageOffShelfService.lambdaUpdate()
                .eq(HxStorageOffShelf::getId, hxStorageOffShelfParam.getId())
                .eq(HxStorageOffShelf::getStatus, "待领取")
                .set(HxStorageOffShelf::getTaskFlag, "急")
                .update();
        return ResponseData.success();
    }
    
}
